package com.jxb.search;

/**
 * 二分查找
 *
 * @author jiaobo
 * @date Created in 2024/12/13 21:04
 **/
public class BinSearch_704 {

    public static void main(String[] args) {

    }

    //循环迭代的方式
    public int search(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int mid = (start + end)/2;
            if (target > nums[mid]) {
                start = mid + 1;
            }else if (target <nums[mid]) {
                end = mid - 1;
            }else {
                return mid;
            }
        }
        return -1;
    }

    //递归
    public int search1(int[] nums, int target) {
        return searchNums(nums,0,nums.length-1,target);
    }

    private int searchNums(int[] nums, int s, int e, int target) {
        int mid = (s+e)/2;
        if (s <= e) {
            if (target > nums[mid])
                return searchNums(nums,mid+1,e,target);
            else if (target<nums[mid])
                return searchNums(nums,s,mid-1,target);
            else
                return mid;
        }else {
            return -1;
        }
    }

}
